package com.np.demo1.thread1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

public class Index {
    // 线程操作 List
    public void test1() {
        int size = 50000;
        List<Integer> list = new ArrayList<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (list.size() == size) break;

                    System.out.println(list.size());
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < size; i++) {
                    list.add(i);
                }
            }
        }).start();
    }

    // 线程操作队列
    public void test2() {
        LinkedBlockingQueue<Long> queue = new LinkedBlockingQueue<Long>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    queue.add(System.currentTimeMillis());
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Long time = queue.take();
                        System.out.println(time);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }

    boolean runable = true;//线程退出标识
    long times1 = 0;//线程1运行次数
    long times2 = 0;//线程2运行次数

    public void test3() {

        Thread th1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (runable) {
                    times1++;
                    System.out.println(Thread.currentThread().getId());
                }
            }
        });

        th1.start();

        Thread th2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (runable) {
                    times2++;
                    System.out.println(Thread.currentThread().getId());
                }
            }
        });
        th2.start();

        try {
            Thread.sleep(1000);
            runable = false;
            System.out.println(times1 + "," + times2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
